package com.iwhalecloud.bss.kite.cucc.order.accept.process.impl;

import com.iwhalecloud.bss.kite.common.chain.HandlerExecutionChain;
import com.iwhalecloud.bss.kite.common.chain.IHandler;
import com.iwhalecloud.bss.kite.cucc.order.accept.process.IOrderBusinessProcessor;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.util.Assert;

import java.util.List;

public abstract class AbstractOrderBusinessProcessor implements IOrderBusinessProcessor, CommandLineRunner {

    protected HandlerExecutionChain<OrderRequest> chain;

    /**
     * 应用启动完成后执行
     */
    @Override
    public void run(String... args) {
        registerHandlers();
    }

    @Override
    public void registerHandlers() {
        List<IHandler<OrderRequest>> handlers = loadHandlers();
        if (CollectionUtils.isEmpty(handlers)) {
            // 如果没有配置，使用默认处理器
            handlers = listDefaultHandlers();
        }

        // 有可能在调度过程中刷新处理器，此处重新new一个调用链对象，不影响正在调度的流程
        HandlerExecutionChain<OrderRequest> newChain = new HandlerExecutionChain<>();
        newChain.addHandlers(handlers);

        chain = newChain;
    }

    @Override
    public void doHandle(OrderRequest orderRequest) {
        Assert.notNull(chain, "chain can not be null, please register the handlers");
        chain.doHandle(orderRequest);
    }

    /**
     * 加载处理器(数据库配置)
     * @return
     */
    protected List<IHandler<OrderRequest>> loadHandlers() {
        return null;
    }

    /**
     * 获取默认处理器
     * @return
     */
    protected abstract List<IHandler<OrderRequest>> listDefaultHandlers();
}
